// pages/personInfo/personInfo.js
import WxValidate from '../../utils/WxValidate'
import utils from "../../utils/util"
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: null,
    message: null,
    genderArray: ['男', '女', '暂不设置'],
    genderIndex: 0,
  },
  //注销登录 
  quit() {
    wx.removeStorageSync('userInfo');
    app.globalData.userInfo = null;
    wx.switchTab({
      url: '../person/person',
    }).then(res => {
      utils.pageOnLoad()
    })
  },
  selectAddress() {
    wx.navigateTo({
      url: '../addres/addres',
    })
  },

  chooseavatar(e) {
    // console.log(e.detail);
    wx.uploadFile({
      filePath: e.detail.avatarUrl,
      name: 'img',
      url: `${app.globalData.server}/uploadImg`,
      success: (result) => { //成功回调
        console.log(result)
        let filePath = JSON.parse(result.data).path;
        filePath = filePath.replace(/\\/g, '/');
        let userInfo = this.data.userInfo;
        userInfo.avatarUrl = `${app.globalData.server}/${filePath}`;
        this.setData({
          userInfo: userInfo
        })
        wx.hideLoading({})
        wx.showToast({
          title: '上传成功',
          icon: "success"
        })
      },
      fail: (e) => {
        //失败回调 
        console.log(e)
        wx.hideLoading({})
        wx.showToast({
          title: '上传失败',
          icon: "error"
        })
      }
    })
  },
  //昵称、手机号,输入框防抖 
  timeID: 0, //定时器ID 
  handleInput(state) {
    console.log(state)
    const {
      name
    } = state.currentTarget.dataset //获取绑定的data-name属性值 
    const {
      value
    } = state.detail //获取输入的值 
    clearTimeout(this.timeID); //清除timeID对应的定时器，取消相应函数的执行 
    this.timeID = setTimeout(() => {
      switch (name) {
        case 'nickName':
          this.setData({
            "userInfo.nickName": value
          });
          break;
        case 'phone':
          this.setData({
            "userInfo.phone": value
          });
          break;
        case 'email':
          this.setData({
            'userInfo.email': value
          })
          break;
      }
    }, 1000)
  },
  //性别改变
  genderChange(e) {
    const index = e.detail.value;
    this.setData({
      genderIndex: index,
      "userInfo.gender": this.data.genderArray[index],
    });
  },

  //真正提交表达
  realSubmitForm(){
    //params保存需要验证的数据对象 
    const params = this.data.userInfo;
                //加载中 
                wx.showLoading()
                //向服务端发送请求 
                wx.request({
                  url: `${app.globalData.server}/wxUpdateUserInfo`,
                  method: 'POST',
                  data: {
                    openid: params.openid,
                    avatarUrl: params.avatarUrl,
                    nickName: params.nickName,
                    phone: params.phone,
                    email: params.email,
                    gender: params.gender,
                    //params
                  },
                  success: res => {
                    wx.hideLoading()
                    //console.log(res) 
                    if (res.data.status === 'success') {
                      //写入缓存 
                      wx.setStorageSync('userInfo', params)
                      //更新全局变量 
                      app.globalData.userInfo = params
                      //提示 
                      wx.showToast({
                        title: '修改成功',
                        icon: 'success'
                      })
                      //跳转至个人中心页面 
                      setTimeout(() => {
                        wx.switchTab({
                          url: '../person/person',
                        })
                      }, 1000)
                    } else {
                      //提示 
                      wx.showToast({
                        title: '修改失败',
                        icon: 'error'
                      })
                    }
                  },
                  fail: err => {
                    wx.hideLoading()
                    console.log(err)
                    //提示 
                    wx.showToast({
                      title: '修改失败',
                      icon: 'error'
                    })
                  }
                })
  },

  //保存表单 
  submitForm() {
    const {
      gender
    } = this.data.userInfo;
    //params保存需要验证的数据对象 
    const params = this.data.userInfo;
    //表单验证 
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0];
      this.showValidateModal(error);
      return false;
    }
    if (this.data.originGender === '暂不设置' && gender !== '暂不设置') {
      wx.showModal({
        title: '注意',
        content: `性别仅可修改一次！您当前选择的性别为:${gender}`,
        complete: (res) => {
          if (res.cancel) {
            this.setData({
              "userInfo.gender": '暂不设置'
            })
            return;
          }
          if (res.confirm) {
            this.realSubmitForm();
          }
        }
      })
    } else{
      this.realSubmitForm();
    }

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const userInfo = wx.getStorageSync('userInfo');
    this.setData({
      userInfo,
      originGender: userInfo.gender
    })
    //加载表单验证规则 
    this.initValidate();
  },
  //初始化验证规则 
  initValidate() {
    // 验证字段的规则 
    const rules = {
      nickName: {
        required: true,
        maxlength: 10
      },
      phone: {
        required: true,
        tel: true
      },
      email: {
        required: false,
        email: true
      }
    }
    // 验证字段的提示信息，若不传则调用默认的信息 
    const messages = {
      nickName: {
        required: '请输入昵称',
        maxlength: '昵称不能超过10个字符'
      },
      phone: {
        required: '请授权手机号',
        tel: '请输入正确的手机号码'
      },
      /* 使用默认
      email: {
        email: '请输入正确的邮箱地址'
      }
      */
    }
    // 创建实例对象 
    this.WxValidate = new WxValidate(rules, messages)
  },
  //表单验证错误提示 
  showValidateModal(error) {
    wx.showModal({
      content: error.msg,
      showCancel: false,
    })
  },

  /**
   * 获取手机号
   * @param {*} e 
   */
  getrealphonenumber(e) {
    const {
      code
    } = e.detail;
    console.log(code)
    wx.request({
      url: `${app.globalData.server}/wxGetPhoneNumber`,
      method: 'POST',
      data: {
        code
      },
      success: (res) => {
        this.setData({
          "userInfo.phone": res.data.data.purePhoneNumber
        });
      },
      fail: () => {
        this.setData({
          message: '请求失败，请重试'
        });
      }
    });
  }
})